package cn.wizzer.app.web.modules.controllers.user;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jsms.api.SendSMSResult;
import cn.jsms.api.common.SMSClient;
import cn.jsms.api.common.model.SMSPayload;
import cn.wizzer.app.match.modules.models.constant.RedisKey;
import cn.wizzer.app.sys.modules.services.SysParamService;
import cn.wizzer.app.user.modules.services.UserService;
import cn.wizzer.app.web.commons.ulog.annotation.ULog;
import cn.wizzer.framework.base.Result;
import cn.wizzer.util.CommonUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.nutz.dao.Cnd;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;


@Api("手机验证码发送")
@IocBean
@At("/api/jiguang")
public class ApiJiGuangController {

    @Reference
    @Inject
    private UserService userService;

    @Reference
    @Inject
    private SysParamService sysParamService;
    @ Inject
    private RedisService redisService;

    private static final Log log = Logs.get();
    @ApiOperation(value = "发送验证码", notes = "返回messageId ", httpMethod = "POST")
    @At("/send")
    @Ok("json")
    @ULog(tag = "发送验证码", msg = "手机号: ${phone}")
    public Result sendCode(@ApiParam(required = true, value = "phone")@Param("phone") String phone,
                           @ApiParam(required = true, value = "type")@Param("type") String type) {
        int num = userService.count(Cnd.where("phone", "=", Strings.trim(phone)));
        if ("register".equals(type) && num > 0) {
            return Result.error("手机号码已注册!");
        } else if("resetPassword".equals(type) && num == 0){
            return Result.error("手机号码未注册");
        }

        // 校验手机号码
        CommonUtil.isPhone(phone);

        SMSClient client = new SMSClient(sysParamService.fetch().getJgMasterSecret(), sysParamService.fetch().getJgAppKey());
        SMSPayload payload = SMSPayload.newBuilder()
                .setMobileNumber(phone) // 手机号码
                .setSignId(11721)               // 签名ID
                .setTempId(1)                   // 短信模板ID,需要自己去申请
                .build();
        try {
            String key = "msgId#phone:" + phone;
            //该手机号是否在一分钟内已获取过短信验证码
            if (redisService.get(key) != null) {
                return Result.error("请勿频繁获取短信验证码");
            }
            SendSMSResult res = client.sendSMSCode(payload);
            log.info(res.toString());
            NutMap resmap = new NutMap();
            resmap.addv("msgId",res.getMessageId());
            //加入redis中用以查询验证
            redisService.set(key,res.getMessageId());
            redisService.expire(key, RedisKey.S_60);
            return Result.success("验证码发送成功",resmap);
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Message: " + e.getMessage());
        }
        return null;
    }


}
